import { useCrudForm } from "@/composables/useCrudForm";
import { transferFormConfig, validateDynamicForm } from "../form-config";
import { formatDateTime } from "@/utils/xenUtils";
import SysHrTransferRequestBillApi from "../api/index";
import commonApi from "@/api/common";
import { reactive } from "vue";
import type {
  ISysHrTransferRequestBill,
  ISysHrTransferRequestBillVm,
} from "../api/interface";

/**
 * 调岗调薪申请单信息专用 Composable
 */
export function useTransferInfo() {
  // 创建API实例
  const api = SysHrTransferRequestBillApi();

  // API配置
  const apiConfig = {
    search: api.search,
    get: api.get,
    add: api.add,
    edit: api.edit,
    delete: api.delete,
    // 单据编号接口 - 适配器处理类型差异
    getBillCode: async () => {
      const result = await api.getBillCode();
      return { Data: result.Data || "" };
    },
  };

  // 选项数据加载器
  const optionLoaders = {
    groupId: async () => {
      const commonApiInstance = commonApi();
      const result = await commonApiInstance.GetParentsTree(false);
      // 转换为useCrudForm期望的格式
      return result.map((item: any) => ({
        Value: item.Value,
        Text: item.Text,
      }));
    },
    personId: async () => {
      // 返回空数组，人员选择通过自动补全搜索实现
      return [];
    },
    newGroupId: async () => {
      const commonApiInstance = commonApi();
      const result = await commonApiInstance.GetParentsTree(false);
      // 转换为useCrudForm期望的格式
      return result.map((item: any) => ({
        Value: item.Value,
        Text: item.Text,
      }));
    },
    newJobPositionId: async () => {
      // 工作岗位需要根据部门动态加载，这里返回空数组
      return [];
    },
  };

  /**
   * 提取文件ID（用于API提交）
   */
  const extractFileId = (fileData: any): string | null => {
    if (!fileData) return null;

    // 如果是单个文件对象
    if (typeof fileData === 'object' && fileData.fileID) {
      return fileData.fileID;
    }

    // 如果是文件数组，取第一个
    if (Array.isArray(fileData) && fileData.length > 0 && fileData[0].fileID) {
      return fileData[0].fileID;
    }

    return null;
  };

  /**
   * 搜索员工（自动补全用）
   */
  const searchEmployees = async (query: string) => {
    try {
      // 判断输入的是工号还是姓名
      // 如果输入的是纯数字，则按工号搜索；否则按姓名搜索
      const isStaffNo = /^\d+$/.test(query.trim());

      // 根据输入类型构建搜索参数
      const searchParams: any = {
        PageIndex: 1,
        State: '在职' // 只搜索在职员工
      };

      // 根据输入类型设置搜索字段
      if (isStaffNo) {
        searchParams.StaffNo = query;
      } else {
        searchParams.Name = query;
      }

      // 使用新的员工搜索API
      const response = await api.searchPersons(searchParams);

      // 检查响应是否成功
      if (response.Code !== 200 || !response.Data) {
        return [];
      }

      // 转换为自动补全组件期望的格式
      return response.Data.map((person: any) => ({
        value: person.ID,
        text: person.Name,
        subtitle: `工号: ${person.StaffNo}${person.GroupName ? ` | ${person.GroupName}` : ''}`, // 显示工号和部门作为副标题
        // 扩展数据，包含公司和部门信息
        extData: {
          staffNo: person.StaffNo,
          orgId: person.OrgId || person.Org?.ID,
          orgName: person.OrgName || person.Org?.Name,
          groupId: person.GroupId || person.Group?.ID,
          groupName: person.GroupName || person.Group?.GroupName,
        }
      }));
    } catch (error) {
      // 搜索失败时返回空数组
      console.warn('员工搜索失败:', error);
      return [];
    }
  };

  // 为personId字段配置searchApi
  if (transferFormConfig.personId) {
    transferFormConfig.personId.searchApi = searchEmployees;
  }

  // 使用通用CRUD表单
  const crudForm = useCrudForm<ISysHrTransferRequestBill, ISysHrTransferRequestBillVm>(
    transferFormConfig,
    apiConfig,
    optionLoaders
  );

  // 岗位选项的局部状态管理（使用响应式对象）
  const positionOptions = reactive({
    new: [] as { value: string; text: string; salary?: number }[],
    original: [] as { value: string; text: string; salary?: number }[]
  });

  // 初始化调整类型默认值为"岗位调整"
  if (!crudForm.formData.transferType) {
    crudForm.formData.transferType = "岗位调整";
    crudForm.pickerValues.transferType = "岗位调整"; // 提交值是字符串文字
  }

  // 初始化薪资字段的默认值
  if (!crudForm.formData.originalBaseSalary) {
    crudForm.formData.originalBaseSalary = "";
  }
  if (!crudForm.formData.originalPositionSalary) {
    crudForm.formData.originalPositionSalary = "";
  }
  if (!crudForm.formData.originalPerformanceSalary) {
    crudForm.formData.originalPerformanceSalary = "";
  }
  if (!crudForm.formData.newBaseSalary) {
    crudForm.formData.newBaseSalary = "";
  }
  if (!crudForm.formData.newPositionSalary) {
    crudForm.formData.newPositionSalary = "";
  }
  if (!crudForm.formData.newPerformanceSalary) {
    crudForm.formData.newPerformanceSalary = "";
  }

  // 初始化新字段的默认值
  if (!crudForm.formData.orgId) {
    crudForm.formData.orgId = "";
  }
  if (!crudForm.formData.orgName) {
    crudForm.formData.orgName = "";
  }
  if (!crudForm.formData.groupName) {
    crudForm.formData.groupName = "";
  }

  // 初始化原职位信息字段
  if (!crudForm.formData.originalGroupName) {
    crudForm.formData.originalGroupName = "";
  }
  if (!crudForm.formData.originalPositionName) {
    crudForm.formData.originalPositionName = "";
  }
  if (!crudForm.formData.originalRank) {
    crudForm.formData.originalRank = "";
  }

  // 初始化新职位信息字段
  if (!crudForm.formData.newGroupName) {
    crudForm.formData.newGroupName = "";
  }
  if (!crudForm.formData.newPositionName) {
    crudForm.formData.newPositionName = "";
  }
  if (!crudForm.formData.newRank) {
    crudForm.formData.newRank = "";
  }

  /**
   * 转换表单数据为API格式（新增）
   */
  const convertFormDataToApiFormatForCreate = (): ISysHrTransferRequestBillVm => {
    return {
      Entity: {
        PersonId: crudForm.pickerValues.personId || null,
        StaffNo: crudForm.formData.staffNo || null,
        Name: crudForm.formData.name || null,
        OrgId: crudForm.pickerValues.orgId || crudForm.formData.orgId || null,
        ApplyDate: crudForm.formData.applyDate ? new Date(crudForm.formData.applyDate) : null,
        EffectiveDate: crudForm.formData.effectiveDate ? new Date(crudForm.formData.effectiveDate) : null,
        TransferType: crudForm.pickerValues.transferType || null,
        TransferReason: crudForm.formData.transferReason || null,
        SupportingDocumentId: extractFileId(crudForm.formData.supportingDocument) || null,
        Approver: null,
        ApprovalTime: null,
        ApprovalOpinion: null,
        // 使用新的字段映射
        GroupId: crudForm.pickerValues.groupId || crudForm.formData.groupId || null,
        BillCode: crudForm.formData.billCode || null,
        // BillStatus和WorkflowStatus不传值，由系统自动设置
        BillStatus: null,
        WorkflowStatus: null,
        Remark: crudForm.formData.remark || null,
        // 职位和薪资信息
        OriginalGroupId: crudForm.pickerValues.originalGroupId || crudForm.formData.originalGroupId || null,
        OriginalPositionId: crudForm.pickerValues.originalPositionId || crudForm.formData.originalPositionId || null,
        OriginalRank: crudForm.formData.originalRank || null,
        OriginalBaseSalary: crudForm.formData.originalBaseSalary || null,
        OriginalPositionSalary: crudForm.formData.originalPositionSalary || null,
        OriginalPerformanceSalary: crudForm.formData.originalPerformanceSalary || null,
        NewGroupId: crudForm.pickerValues.newGroupId || crudForm.formData.newGroupId || null,
        NewPositionId: crudForm.pickerValues.newJobPositionId || crudForm.formData.newJobPositionId || null,
        NewRank: crudForm.formData.newRank || null,
        NewBaseSalary: crudForm.formData.newBaseSalary || null,
        NewPositionSalary: crudForm.formData.newPositionSalary || null,
        NewPerformanceSalary: crudForm.formData.newPerformanceSalary || null,
      } as ISysHrTransferRequestBill,
      ActionName: null,
      IsMyApprove: null,
      Remark: null,
    };
  };

  /**
   * 转换表单数据为API格式（编辑）
   */
  const convertFormDataToApiFormatForEdit = (): ISysHrTransferRequestBillVm => {
    const originalData = crudForm.originalData.value;
    if (!originalData) {
      throw new Error("原始数据不存在");
    }

    return {
      Entity: {
        ID: originalData.ID || null,
        PersonId: crudForm.pickerValues.personId || originalData.PersonId,
        StaffNo: crudForm.formData.staffNo || originalData.StaffNo,
        Name: crudForm.formData.name || originalData.Name,
        OrgId: crudForm.pickerValues.orgId || crudForm.formData.orgId || originalData.OrgId,
        ApplyDate: crudForm.formData.applyDate ? new Date(crudForm.formData.applyDate) : originalData.ApplyDate,
        EffectiveDate: crudForm.formData.effectiveDate ? new Date(crudForm.formData.effectiveDate) : originalData.EffectiveDate,
        TransferType: crudForm.pickerValues.transferType || originalData.TransferType,
        TransferReason: crudForm.formData.transferReason || originalData.TransferReason,
        SupportingDocumentId: extractFileId(crudForm.formData.supportingDocument) || originalData.SupportingDocumentId || null,
        Approver: originalData.Approver,
        ApprovalTime: originalData.ApprovalTime,
        ApprovalOpinion: originalData.ApprovalOpinion,
        // 使用新的字段映射
        GroupId: crudForm.pickerValues.groupId || crudForm.formData.groupId || originalData.GroupId,
        BillCode: crudForm.formData.billCode || originalData.BillCode,
        // BillStatus和WorkflowStatus不传值，由系统自动设置
        BillStatus: '草稿',
        WorkflowStatus: '提交中',
        Remark: crudForm.formData.remark || originalData.Remark,
        // 职位和薪资信息
        OriginalGroupId: crudForm.pickerValues.originalGroupId || crudForm.formData.originalGroupId || originalData.OriginalGroupId,
        OriginalPositionId: crudForm.pickerValues.originalPositionId || crudForm.formData.originalPositionId || originalData.OriginalPositionId,
        OriginalRank: crudForm.formData.originalRank || originalData.OriginalRank,
        OriginalBaseSalary: crudForm.formData.originalBaseSalary || originalData.OriginalBaseSalary,
        OriginalPositionSalary: crudForm.formData.originalPositionSalary || originalData.OriginalPositionSalary,
        OriginalPerformanceSalary: crudForm.formData.originalPerformanceSalary || originalData.OriginalPerformanceSalary,
        NewGroupId: crudForm.pickerValues.newGroupId || crudForm.formData.newGroupId || originalData.NewGroupId,
        NewPositionId: crudForm.pickerValues.newJobPositionId || crudForm.formData.newJobPositionId || originalData.NewPositionId,
        NewRank: crudForm.formData.newRank || originalData.NewRank,
        NewBaseSalary: crudForm.formData.newBaseSalary || originalData.NewBaseSalary,
        NewPositionSalary: crudForm.formData.newPositionSalary || originalData.NewPositionSalary,
        NewPerformanceSalary: crudForm.formData.newPerformanceSalary || originalData.NewPerformanceSalary,
      } as ISysHrTransferRequestBill,
      ActionName: null,
      IsMyApprove: null,
      Remark: null,
    };
  };

  /**
   * 字段映射配置（API字段路径到表单字段的映射）
   */
  const fieldMapping = {
    // 单据信息
    billCode: "BillCode",
    billStatus: "BillStatus",
    workflowStatus: "WorkflowStatus",

    // 调动信息
    personId: "PersonId",
    staffNo: "StaffNo",
    name: "Name",
    orgId: "OrgId", // 原始的公司ID字段
    orgName: "Org.Name",
    groupId: "GroupId",
    groupName: "Group.GroupName",
    applyDate: "ApplyDate",
    effectiveDate: "EffectiveDate",
    transferType: "TransferType",
    transferReason: "TransferReason",
    supportingDocument: "SupportingDocument",

    // 原职位信息
    originalGroupId: "OriginalGroupId",
    originalGroupName: "OriginalGroup.GroupName",
    originalPositionId: "OriginalPositionId",
    originalPositionName: "OriginalPosition.Name",
    originalRank: "OriginalRank",
    originalBaseSalary: "OriginalBaseSalary",
    originalPositionSalary: "OriginalPositionSalary",
    originalPerformanceSalary: "OriginalPerformanceSalary",

    // 调整后信息
    newGroupId: "NewGroupId",
    newGroupName: "NewGroup.GroupName",
    newJobPositionId: "NewPositionId",
    newPositionName: "NewPosition.Name",
    newRank: "NewRank",
    newBaseSalary: "NewBaseSalary",
    newPositionSalary: "NewPositionSalary",
    newPerformanceSalary: "NewPerformanceSalary",

    // 流程信息
    approver: "Approver",
    approvalTime: "ApprovalTime",
    approvalOpinion: "ApprovalOpinion",

    remark: "Remark",

    // 保留原有字段映射以兼容
    group: "Group.GroupName",
  };

  /**
   * 加载调岗调薪申请单详情数据
   */
  const loadTransferDetail = async (id: string): Promise<{ success: boolean; isMyApprove?: boolean }> => {
    try {
      // 直接调用API获取完整响应
      const response = await api.get(id);

      if (response && response.Entity) {
        const detail = response.Entity;

        // 设置原始数据
        crudForm.originalData.value = detail;

        // 检查原始数据中的日期字段
        const dateFields = ["ApprovalTime", "ApplyDate", "EffectiveDate"];
        dateFields.forEach(field => {
          if ((detail as any)[field]) {
          }
        });

        // 先使用通用转换
        crudForm.convertApiDataToFormData(detail, fieldMapping);

        // 添加特殊处理，确保选择器字段正确映射
        await ensurePickerFieldsMapping(detail);

        return {
          success: true,
          isMyApprove: response.IsMyApprove || false
        };
      }
      return { success: false };
    } catch (error) {
      return { success: false };
    }
  };

  /**
   * 确保选择器字段正确映射
   */
  const ensurePickerFieldsMapping = async (apiData: any) => {
    // 处理单据编号
    if (apiData.BillCode) {
      crudForm.formData.billCode = apiData.BillCode;
    }

    // 处理单据状态
    if (apiData.BillStatus !== undefined) {
      const statusText = apiData.BillStatus === "草稿" ? "草稿" : "正文";
      crudForm.formData.billStatus = statusText;
      crudForm.pickerValues.billStatus = apiData.BillStatus.toString();
    }

    // 处理工作流状态显示
    if (apiData.WorkflowStatus !== undefined) {
      crudForm.formData.workflowStatus = apiData.WorkflowStatus || "";
    }

    // 处理调整类型
    if (apiData.TransferType !== undefined) {
      // 如果后端返回的是字符串，直接使用
      if (typeof apiData.TransferType === 'string') {
        crudForm.formData.transferType = apiData.TransferType;
        crudForm.pickerValues.transferType = apiData.TransferType;
      }
      // 兼容后端可能返回数字的情况
      else if (typeof apiData.TransferType === 'number') {
        const typeTexts = ["岗位调整", "薪资调整", "岗位和薪资调整", "晋升", "降级"];
        if (apiData.TransferType >= 0 && apiData.TransferType < typeTexts.length) {
          const transferTypeText = typeTexts[apiData.TransferType];
          crudForm.formData.transferType = transferTypeText;
          crudForm.pickerValues.transferType = transferTypeText;
        }
      }
    }

    // 处理所属部门
    if (apiData.GroupId) {
      // 对于department-picker类型，formData中存储部门ID（用于组件显示选中状态）
      crudForm.formData.groupId = apiData.GroupId;
      crudForm.pickerValues.groupId = apiData.GroupId;
    }

    // 处理员工信息

    // 始终从API数据设置员工姓名，确保有值显示
    if (apiData.Name) {
      // 设置autocomplete组件显示的文本（编辑页显示员工姓名）
      crudForm.formData.personId = apiData.Name;
    }

    // 设置实际的员工ID用于提交
    if (apiData.PersonId) {
      crudForm.pickerValues.personId = apiData.PersonId;
    }

    // 如果有选项数据，也尝试匹配设置
    if (apiData.PersonId && transferFormConfig.personId?.optionsData) {
      const personOption = transferFormConfig.personId.optionsData.find(
        (option: any) => option.value === apiData.PersonId
      );
      if (personOption) {
        crudForm.formData.personId = personOption.text;
        crudForm.pickerValues.personId = apiData.PersonId;
      }
    }

    // 处理员工工号和姓名（从API数据直接获取）
    if (apiData.StaffNo) {
      crudForm.formData.staffNo = apiData.StaffNo;
    }
    if (apiData.Name) {
      crudForm.formData.name = apiData.Name;
    }

    // 处理公司信息
    if (apiData.OrgId) {
      crudForm.formData.orgId = apiData.OrgId;
      crudForm.pickerValues.orgId = apiData.OrgId;
    }
    if (apiData.Org?.Name || apiData.OrgName) {
      crudForm.formData.orgName = apiData.Org?.Name || apiData.OrgName;
    }

    // 处理所属部门信息
    if (apiData.GroupId) {
      crudForm.formData.groupId = apiData.GroupId;
      crudForm.pickerValues.groupId = apiData.GroupId;
    }
    if (apiData.Group?.GroupName || apiData.GroupName) {
      crudForm.formData.groupName = apiData.Group?.GroupName || apiData.GroupName;
    }

    // 处理审批时间格式化
    if (apiData.ApprovalTime) {
      crudForm.formData.approvalTime = formatDateTime(apiData.ApprovalTime);
    }

    // 处理申请日期格式化
    if (apiData.ApplyDate) {
      const formattedDateTime = formatDateTime(apiData.ApplyDate);
      crudForm.formData.applyDate = formattedDateTime ? formattedDateTime.split(' ')[0] : '';
    }

    // 处理生效日期格式化
    if (apiData.EffectiveDate) {
      const formattedDateTime = formatDateTime(apiData.EffectiveDate);
      crudForm.formData.effectiveDate = formattedDateTime ? formattedDateTime.split(' ')[0] : '';
    }

    // 处理工作流状态
    if (apiData.WorkflowStatus !== undefined) {
      crudForm.formData.workflowStatus = apiData.WorkflowStatus || "";
    }

    // 处理审批人
    if (apiData.Approver) {
      crudForm.formData.approver = apiData.Approver;
    }

    // 处理审批意见
    if (apiData.ApprovalOpinion) {
      crudForm.formData.approvalOpinion = apiData.ApprovalOpinion;
    }

    // 处理证明文件回显
    if (apiData.SupportingDocumentId) {
      const getFileUrl = (fileId: string | null) => {
        if (!fileId) return "";
        return `${import.meta.env.VITE_BASE_URL}/api/_file/getfile/${fileId}`;
      };

      const fileInfo = {
        name: "证明文件",
        url: getFileUrl(apiData.SupportingDocumentId),
        extname: "pdf",
        size: 0,
        fileID: apiData.SupportingDocumentId,
        id: apiData.SupportingDocumentId, // attachment-upload 组件需要 id 字段
      };
      // attachment-upload 组件期望数组格式
      crudForm.formData.supportingDocument = [fileInfo];
    } else {
      crudForm.formData.supportingDocument = [];
    }

    // 处理原职位信息
    crudForm.formData.originalGroupName = apiData.OriginalGroup?.GroupName || "";
    crudForm.formData.originalPositionName = apiData.OriginalPosition?.Name || "";
    crudForm.formData.originalRank = apiData.OriginalRank || "";

    // 处理新职位信息
    crudForm.formData.newGroupName = apiData.NewGroup?.GroupName || "";
    crudForm.formData.newPositionName = apiData.NewPosition?.Name || "";
    crudForm.formData.newRank = apiData.NewRank || "";

    // 处理薪资信息 - 确保字段始终存在，即使为空值
    crudForm.formData.originalBaseSalary = apiData.OriginalBaseSalary || "";
    crudForm.formData.originalPositionSalary = apiData.OriginalPositionSalary || "";
    crudForm.formData.originalPerformanceSalary = apiData.OriginalPerformanceSalary || "";
    crudForm.formData.newBaseSalary = apiData.NewBaseSalary || "";
    crudForm.formData.newPositionSalary = apiData.NewPositionSalary || "";
    crudForm.formData.newPerformanceSalary = apiData.NewPerformanceSalary || "";
  };

  /**
   * 创建调岗调薪申请单（两步提交流程）
   * 第一步：调用Add接口保存草稿
   * 第二步：调用Edit接口提交
   */
  const createTransfer = async (): Promise<{
    success: boolean;
    data?: ISysHrTransferRequestBill;
    validation?: { valid: boolean; errors: Record<string, string>; firstErrorMessage?: string };
    error?: string;
  }> => {
    // 使用动态验证，只验证当前显示的字段
    const transferType = crudForm.formData.transferType || "";
    const validationResult = validateDynamicFormFields(transferType, 'create');

    if (!validationResult.valid) {
      // 显示第一个错误信息
      if (validationResult.firstErrorMessage) {
        uni.showToast({
          title: validationResult.firstErrorMessage,
          icon: "none",
          duration: 2000
        });
      }

      return {
        success: false,
        validation: validationResult
      };
    }

    try {
      // 第一步：调用Add接口保存草稿
      const apiData = convertFormDataToApiFormatForCreate();
      const addResult = await crudForm.create(apiData);

      if (!addResult || !addResult.ID) {
        return {
          success: false,
          validation: validationResult,
          error: "保存草稿失败，请重试"
        };
      }

      // 第二步：调用Edit接口进行提交
      // 设置原始数据为第一步返回的结果，用于Edit接口
      crudForm.originalData.value = addResult;

      // 创建编辑数据格式进行提交
      const editApiData = convertFormDataToApiFormatForEdit();

      const editResult = await crudForm.update(editApiData);

      if (!editResult) {
        return {
          success: false,
          validation: validationResult,
          error: "提交失败，数据已保存为草稿，请稍后重试"
        };
      }

      return {
        success: true,
        data: editResult,
        validation: validationResult
      };

    } catch (error) {
      return {
        success: false,
        validation: validationResult,
        error: "提交过程中发生错误，请重试"
      };
    }
  };

  /**
   * 保存调岗调薪申请单（编辑）
   */
  const saveTransfer = async (): Promise<{
    success: boolean;
    data?: ISysHrTransferRequestBill;
    validation?: { valid: boolean; errors: Record<string, string>; firstErrorMessage?: string };
    error?: string;
  }> => {
    const validationResult = crudForm.validateAllFieldsWithDetails();

    if (!validationResult.valid) {
      return {
        success: false,
        validation: validationResult
      };
    }

    // 验证关键数据
    if (!crudForm.originalData.value) {
      return {
        success: false,
        error: "原始数据丢失，请重新加载页面",
        validation: validationResult
      };
    }

    const apiData = convertFormDataToApiFormatForEdit();
    const result = await crudForm.update(apiData);

    return {
      success: result !== null,
      data: result || undefined,
      validation: validationResult
    };
  };

  /**
   * 更新表单配置中的部门数据
   */
  const updateDepartmentData = async () => {
    try {
      const commonApiInstance = commonApi();
      const departmentData = await commonApiInstance.GetParentsTree(false);

      // 更新表单配置中的部门数据，使用深度锁定确保数据不会被重写
      const deptData = departmentData || [];
      const optionsData = deptData.map((item: any) => ({
        value: item.Value,
        text: item.Text,
      }));

      if (transferFormConfig.originalGroupId) {
        transferFormConfig.originalGroupId.departmentData = [...deptData];
        transferFormConfig.originalGroupId.optionsData = [...optionsData];
      }

      if (transferFormConfig.newGroupId) {
        transferFormConfig.newGroupId.departmentData = [...deptData];
        transferFormConfig.newGroupId.optionsData = [...optionsData];
      }

      return departmentData || [];
    } catch (error: any) {
      return [];
    }
  };

  /**
   * 检查并确保部门数据可用（用于解决调整类型切换时的数据丢失问题）
   */
  const ensureDepartmentDataAvailable = async (): Promise<boolean> => {
    const hasOriginalData = (transferFormConfig.originalGroupId?.departmentData?.length || 0) > 0;
    const hasNewData = (transferFormConfig.newGroupId?.departmentData?.length || 0) > 0;

    if (!hasOriginalData || !hasNewData) {
      try {
        await updateDepartmentData();
        return true;
      } catch (error) {
        return false;
      }
    }
    return true;
  };

  /**
   * 根据部门ID加载岗位列表
   */
  const loadPositionsByDepartment = async (departmentId: string): Promise<void> => {
    if (!departmentId) {
      // 如果没有部门ID，清空岗位选项
      positionOptions.new = [];
      return;
    }

    try {
      const positions = await api.getSysJobPositions(departmentId);

      const positionOptionsList = positions.map((position: any) => ({
        value: position.Value || position.Id,
        text: position.Text || position.Name,
        salary: position.Salary || 0, // 添加薪资信息
      }));

      // 更新局部状态
      positionOptions.new = positionOptionsList;

      // 同时更新表单配置中的选项数据，这样convertApiDataToFormData才能正确处理
      if (transferFormConfig.newJobPositionId) {
        transferFormConfig.newJobPositionId.options = positionOptionsList.map(option => option.text);
        transferFormConfig.newJobPositionId.optionsData = positionOptionsList;
      }

    } catch (error) {
      // 加载失败时清空选项
      positionOptions.new = [];
      uni.showToast({
        title: "加载岗位列表失败",
        icon: "none",
      });
    }
  };

  /**
   * 根据部门ID加载原岗位列表
   */
  const loadOriginalPositionsByDepartment = async (departmentId: string): Promise<void> => {
    if (!departmentId) {
      // 如果没有部门ID，清空原岗位选项
      positionOptions.original = [];
      return;
    }

    try {
      const positions = await api.getSysJobPositions(departmentId);

      const positionOptionsList = positions.map((position: any) => ({
        value: position.Value || position.Id,
        text: position.Text || position.Name,
        salary: position.Salary || 0, // 添加薪资信息
      }));

      // 更新局部状态
      positionOptions.original = positionOptionsList;

      // 同时更新表单配置中的选项数据
      if (transferFormConfig.originalPositionId) {
        transferFormConfig.originalPositionId.options = positionOptionsList.map(option => option.text);
        transferFormConfig.originalPositionId.optionsData = positionOptionsList;
      }

    } catch (error) {
      // 加载失败时清空选项
      positionOptions.original = [];
      uni.showToast({
        title: "加载原岗位列表失败",
        icon: "none",
      });
    }
  };

  /**
   * 处理部门选择变化，自动加载对应岗位
   */
  const handleDepartmentChange = async (fieldKey: string, departmentId: string): Promise<void> => {

    // 如果是新部门变化，清空新岗位选择并重新加载
    if (fieldKey === "newGroupId") {
      // 清空新岗位选择
      crudForm.formData.newJobPositionId = "";
      crudForm.pickerValues.newJobPositionId = "";

      // 加载对应岗位（包括清空的情况）
      await loadPositionsByDepartment(departmentId);
    } else if (fieldKey === "originalGroupId") {
      // 原部门变化，清空原岗位选择并重新加载
      crudForm.formData.originalPositionId = "";
      crudForm.pickerValues.originalPositionId = "";

      // 为原岗位加载对应岗位选项
      if (departmentId) {
        await loadOriginalPositionsByDepartment(departmentId);
      } else {
        // 清空原岗位选项
        positionOptions.original = [];
      }
    }
  };

  /**
   * 检查岗位字段是否应该被禁用
   */
  const isPositionFieldDisabled = (fieldKey: string): boolean => {
    if (fieldKey === "newJobPositionId") {
      return !crudForm.formData.newGroupId && !crudForm.pickerValues.newGroupId;
    } else if (fieldKey === "originalPositionId") {
      return !crudForm.formData.originalGroupId && !crudForm.pickerValues.originalGroupId;
    }
    return false;
  };

  /**
   * 获取岗位选项（用于表单渲染）
   */
  const getPositionOptions = (fieldKey: string): { value: string; text: string }[] => {
    if (fieldKey === "newJobPositionId") {
      return positionOptions.new || [];
    } else if (fieldKey === "originalPositionId") {
      return positionOptions.original || [];
    }
    return [];
  };

  /**
   * 获取岗位选项的显示文本数组（用于picker组件）
   */
  const getPositionOptionsText = (fieldKey: string): string[] => {
    if (fieldKey === "newJobPositionId") {
      const options = getPositionOptions(fieldKey);
      return options.map(option => option.text);
    } else if (fieldKey === "originalPositionId") {
      const options = getPositionOptions(fieldKey);
      return options.map(option => option.text);
    }
    return [];
  };

  /**
   * 重写 initializeOptions 方法，同时更新部门数据
   */
  const initializeOptions = async (): Promise<boolean> => {
    // 先调用原始的 initializeOptions
    const result = await crudForm.initializeOptions();

    // 然后更新部门数据
    await updateDepartmentData();

    return result;
  };

  /**
   * 动态验证表单 - 只验证当前显示的字段
   */
  const validateDynamicFormFields = (
    transferType: string,
    pageType: 'create' | 'edit' | 'details'
  ): { valid: boolean; errors: Record<string, string>; firstErrorMessage?: string } => {
    return validateDynamicForm(crudForm.formData, transferType, pageType);
  };

  /**
   * 处理原岗位选择变化，自动填充原岗位薪资
   */
  const handleOriginalPositionChange = (positionId: string): void => {
    const selectedPosition = positionOptions.original.find((pos: any) => pos.value === positionId);
    if (selectedPosition && selectedPosition.salary !== undefined) {
      // 只有在调整类型为"岗位和薪资调整"、"晋升"、"降级"时才自动填充薪资
      const transferType = crudForm.formData.transferType;
      if (transferType === "岗位和薪资调整" || transferType === "晋升" || transferType === "降级") {
        crudForm.formData.originalPositionSalary = selectedPosition.salary.toString();
        crudForm.pickerValues.originalPositionSalary = selectedPosition.salary.toString();
      }
    }
  };

  /**
   * 处理新岗位选择变化，自动填充新岗位薪资
   */
  const handleNewPositionChange = (positionId: string): void => {
    const selectedPosition = positionOptions.new.find((pos: any) => pos.value === positionId);
    if (selectedPosition && selectedPosition.salary !== undefined) {
      // 只有在调整类型为"岗位和薪资调整"、"晋升"、"降级"时才自动填充薪资
      const transferType = crudForm.formData.transferType;
      if (transferType === "岗位和薪资调整" || transferType === "晋升" || transferType === "降级") {
        crudForm.formData.newPositionSalary = selectedPosition.salary.toString();
        crudForm.pickerValues.newPositionSalary = selectedPosition.salary.toString();
      }
    }
  };

  /**
   * 重写picker变化处理函数，添加岗位选择的特殊处理
   */
  const handlePickerChange = (fieldKey: string, e: any) => {
    // 先调用原始的picker处理逻辑
    crudForm.handlePickerChange(fieldKey, e);

    // 添加岗位选择的特殊处理
    if (fieldKey === "originalPositionId") {
      const selectedValue = crudForm.pickerValues[fieldKey];
      if (selectedValue) {
        handleOriginalPositionChange(selectedValue);
      }
    } else if (fieldKey === "newJobPositionId") {
      const selectedValue = crudForm.pickerValues[fieldKey];
      if (selectedValue) {
        handleNewPositionChange(selectedValue);
      }
    }
  };

  return {
    // 继承通用CRUD表单的所有功能
    ...crudForm,

    // 重写 handlePickerChange 方法
    handlePickerChange,

    // 重写 initializeOptions 方法
    initializeOptions,

    // 调岗调薪申请单信息专用方法
    loadTransferDetail,
    createTransfer,
    saveTransfer,
    updateDepartmentData,
    ensureDepartmentDataAvailable,
    searchEmployees,

    // API数据转换方法
    convertFormDataToApiFormatForCreate,
    convertFormDataToApiFormatForEdit,

    // 部门和岗位联动相关方法
    loadPositionsByDepartment,
    loadOriginalPositionsByDepartment,
    handleDepartmentChange,
    isPositionFieldDisabled,
    getPositionOptions,
    getPositionOptionsText,

    // 动态验证方法
    validateDynamicFormFields,

    // 岗位选择处理方法
    handleOriginalPositionChange,
    handleNewPositionChange,

    // 字段映射
    fieldMapping,
  };
}
